class SoundManager {
    constructor() {
        try {
            // Create audio context
            this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
            
            // Store audio buffers and sources
            this.audioBuffers = {};
            this.audioSources = {};
            this.gainNodes = {};

            // Audio file URLs
            this.audioUrls = {
                correct: 'https://raw.githubusercontent.com/chocoford/chocoford/main/public/bubble.wav',
                wrong: 'https://raw.githubusercontent.com/chocoford/chocoford/main/public/Little%20blip.wav',
                bgm: 'https://raw.githubusercontent.com/chocoford/chocoford/main/public/761766__universfield__joyful-vibrance-uplifting-music-for-animations-and-commercials.mp3'
            };

            // Volume settings
            this.volumes = {
                bgm: 0.24,
                correct: 0.5,
                wrong: 0.7
            };

            // Get initial sound state from localStorage
            this.enabled = localStorage.getItem('soundEnabled') !== 'false';

            // Delay loading audio files
            setTimeout(() => {
                this.loadAudioFiles();
            }, 600);
        } catch (error) {
            reportError(error);
            this.enabled = false;
        }
    }

    async loadAudioFiles() {
        try {
            const loadPromises = Object.entries(this.audioUrls).map(async ([name, url]) => {
                const response = await fetch(url);
                const arrayBuffer = await response.arrayBuffer();
                const audioBuffer = await this.audioContext.decodeAudioData(arrayBuffer);
                this.audioBuffers[name] = audioBuffer;

                // Create gain node for this sound
                const gainNode = this.audioContext.createGain();
                gainNode.connect(this.audioContext.destination);
                gainNode.gain.value = this.volumes[name];
                this.gainNodes[name] = gainNode;
            });

            await Promise.all(loadPromises);
        } catch (error) {
            reportError(error);
        }
    }

    async ensureAudioContext() {
        try {
            if (this.audioContext.state === 'suspended') {
                await this.audioContext.resume();
            }
        } catch (error) {
            reportError(error);
        }
    }

    playSound(soundName) {
        try {
            if (!this.enabled || !this.audioBuffers[soundName]) return;

            this.ensureAudioContext();

            // Stop previous source if it exists
            if (this.audioSources[soundName]) {
                this.audioSources[soundName].stop();
            }

            // Create new source
            const source = this.audioContext.createBufferSource();
            source.buffer = this.audioBuffers[soundName];
            source.connect(this.gainNodes[soundName]);
            
            // Store the source
            this.audioSources[soundName] = source;

            // Start playing
            source.start(0);

            // Clean up when finished
            source.onended = () => {
                if (this.audioSources[soundName] === source) {
                    this.audioSources[soundName] = null;
                }
            };
        } catch (error) {
            reportError(error);
        }
    }

    playBGM() {
        try {
            if (!this.enabled || !this.audioBuffers.bgm) return;

            this.ensureAudioContext();

            // Stop previous BGM if playing
            if (this.audioSources.bgm) {
                this.audioSources.bgm.stop();
            }

            // Create new source
            const source = this.audioContext.createBufferSource();
            source.buffer = this.audioBuffers.bgm;
            source.connect(this.gainNodes.bgm);
            source.loop = true;
            
            // Store the source
            this.audioSources.bgm = source;

            // Start playing
            source.start(0);
        } catch (error) {
            reportError(error);
        }
    }

    stopBGM() {
        try {
            if (this.audioSources.bgm) {
                this.audioSources.bgm.stop();
                this.audioSources.bgm = null;
            }
        } catch (error) {
            reportError(error);
        }
    }

    toggleSound() {
        try {
            this.enabled = !this.enabled;
            localStorage.setItem('soundEnabled', this.enabled);

            if (!this.enabled) {
                this.stopBGM();
            } else {
                this.playBGM();
            }
        } catch (error) {
            reportError(error);
        }
    }

    setVolume(soundName, volume) {
        try {
            if (this.gainNodes[soundName]) {
                this.gainNodes[soundName].gain.value = volume;
                this.volumes[soundName] = volume;
            }
        } catch (error) {
            reportError(error);
        }
    }

    isEnabled() {
        return this.enabled;
    }
}

// Create a singleton instance but delay its instantiation
let soundManager;
setTimeout(() => {
    soundManager = new SoundManager();
}, 600);
